// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'boyi-5g77xpkp0aa0181c'
})

// 云函数入口函数
exports.main = async (event, context) => {
  // 获取微信上下文
  const wxContext = cloud.getWXContext()

  // 实例化数据库
  const db = cloud.database();

  /** 检查是否正确获取用户的openId start */
  if(wxContext.OPENID == undefined) {
    var result = {};
    result.errCode = 1;
    result.errMsg = "未能正确返回openId";
    var data = {};
    result.data = data;
    return result;
  }
  /** 检查是否正确获取用户openId end */

  /** 根据openId从healthReport表中查询出该用户的健康记录 start */
  var today = new Date();
  var record = [];
  await db.collection('healthReport')
  .where({
    openId: wxContext.OPENID,
  })
  .orderBy('date', 'desc')
  .orderBy('timeSlot', 'desc')
  .limit(50)
  .get()
  .then(res => {
    console.log(res.data);
    record = res.data;
  })
  /** 根据openId从healthReport表中查询出该用户的健康记录 end */

  // 返回数据
  var result = {};
  result.errCode =  0;
  result.errMsg = "成功查询";
  var data = {};
  data.record = record;
  result.data = data;
  return result;
}